package com.lightsaber.trade.core.entity.account.nopersist;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.lightsaber.trade.core.interceptor.FunctionInterceptor;

public class MenuBar {
    private List<MenuItem> topLevelMenuItems = new ArrayList<MenuItem>();

    public void putTopLevelMenuItem(final MenuItem topLevelMenuItem) {
        topLevelMenuItems.add(topLevelMenuItem);
    }

    
    @Override
    public String toString() {
        StringBuilder htmlBuf = new StringBuilder();

        htmlBuf.append("<div class='sf-topMenu'><div class='sf-rBorder'> <div class='topMenu'><ul id='menu-1' class='sf-menu'>");

        // Get root context path from request URL
        HttpServletRequest request = ServletActionContext.getRequest();
        String rootContext = request.getContextPath();

        recursionMenuItem(topLevelMenuItems, htmlBuf, rootContext);

        htmlBuf.append("</ul></div></div></div>");
        return htmlBuf.toString();
    }

    public void recursionMenuItem(final List<MenuItem> menuItems, final StringBuilder htmlBuf,
            final String rootContext) {
        Collections.sort(menuItems);

        for (MenuItem menuItem : menuItems) {
            if (menuItem.isLeaf()) {
                htmlBuf.append("<li><a id='" + menuItem.getId() + "' href='" + rootContext + "/"
                        + getLink(menuItem.getHref(), menuItem.getId()) + "' > ");
                htmlBuf.append(menuItem.getLabel());
                htmlBuf.append("</a></li>");
            } else {

                htmlBuf.append("<li class='link'><a id='" + menuItem.getId()
                        + "' class='sf-with-ul' href='javascript:void(0)' >" + menuItem.getLabel()
                        + " <span class='sf-sub-indicator'> &#187;</span></a><ul>");

                recursionMenuItem(menuItem.getChildren(), htmlBuf, rootContext);

                htmlBuf.append(" </ul></li>");
            }
        }
    }

    public static String getLink(String menuUrl, String function) {
		if(menuUrl==null){
			return "#?" + FunctionInterceptor.MENU_FUNC + "=" + function;
		}
        if (menuUrl.indexOf('?') > -1) {
            return menuUrl + "&" + FunctionInterceptor.MENU_FUNC + "=" + function;
        }
        return menuUrl + "?" + FunctionInterceptor.MENU_FUNC + "=" + function;
    }

}
